from datetime import datetime
from app import db

class Project(db.Model):
    __tablename__ = 'projects'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    start_date = db.Column(db.Date, nullable=False)
    end_date = db.Column(db.Date)
    progress = db.Column(db.Float, default=0.0)
    status = db.Column(db.String(20), default='active')  # active, completed, on_hold, cancelled
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系
    objective_links = db.relationship('ProjectObjectiveLink', backref='project', lazy='dynamic', cascade='all, delete-orphan')
    progress_updates = db.relationship('ProgressUpdate', backref='project', lazy='dynamic')

    def link_to_objective(self, objective_id, weight=1.0):
        """关联项目到目标"""
        link = ProjectObjectiveLink(
            project_id=self.id,
            objective_id=objective_id,
            contribution_weight=weight
        )
        db.session.add(link)
        return link

    def get_linked_objectives(self):
        """获取所有关联的目标"""
        return [link.objective for link in self.objective_links.all()]

    def to_dict(self, include_objectives=False):
        data = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'owner_id': self.owner_id,
            'owner': {
                'id': self.owner.id,
                'full_name': self.owner.full_name,
                'username': self.owner.username
            } if self.owner else None,
            'start_date': self.start_date.isoformat() if self.start_date else None,
            'end_date': self.end_date.isoformat() if self.end_date else None,
            'progress': round(self.progress, 2),
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }

        if include_objectives:
            data['linked_objectives'] = [
                {
                    'id': link.id,
                    'objective_id': link.objective.id,
                    'objective': {
                        'id': link.objective.id,
                        'title': link.objective.title,
                        'type': link.objective.type,
                        'level': link.objective.level
                    },
                    'weight': link.contribution_weight
                }
                for link in self.objective_links.all()
            ]

        return data


class ProjectObjectiveLink(db.Model):
    __tablename__ = 'project_objective_links'

    id = db.Column(db.Integer, primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    objective_id = db.Column(db.Integer, db.ForeignKey('objectives.id'), nullable=False)
    contribution_weight = db.Column(db.Float, default=1.0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    __table_args__ = (db.UniqueConstraint('project_id', 'objective_id', name='_project_objective_uc'),)

    def to_dict(self):
        return {
            'id': self.id,
            'project_id': self.project_id,
            'objective_id': self.objective_id,
            'contribution_weight': self.contribution_weight,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }